<?php

namespace app\admin\controller\ykjp\sell;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Rfinancial extends Backend {

    /**
     * Rfinancial模型对象
     * @var \app\admin\model\sell\Rfinancial
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\sell\Rfinancial;
        $this->view->assign("statusListList", $this->model->getStatusListList());
    }

    /**
     * 详情
     */
    public function detail() {
        $ids = $this->request->param("ids");
        if ($ids == "") {
            $this->error("fail", "ykjp/sell/Sellreturn/index");
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = Db::name('ykjp_sell_return')
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->where("id", $ids)
                ->select();

        $dModel = new \app\admin\model\ykjp\sell\returnPro;
        $strProduct = $dModel->with(['products'])->where("sell_return_id", $ids)->where('products.firmid', $this->auth->firmid)->select();
        // halt($strProduct);

        $this->assign("detail", $list);
        $this->assign("product", $strProduct);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function approval($ids = null) {

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        //判断通过还是驳回 （pass 通过  reject 驳回)
        if ($this->request->param("type") == "yes") {  //通过
            $time = time();
            $data = array("status_list" => 5, "reviewer_id" => $this->auth->id, "updatetime" => $time);
            /*
              首先修改出库单状态，然后
              通过前台传递过来的ids列表查询销售出库单的‘销售单ID’字段和《销售出库单副表》，获取销售出库单副表中的‘出库数量’、‘关联表id’和‘产品ID’字段。
              根据获取的字段:
              更新销售单表
              插入流水表
              更新关联表
              更新商品表
              更新仓库表
              更新库区表
             */

            //获取 销售退货单的‘销售单ID’字段
            $sell_id_arr = Db::name('ykjp_sell_return')->field('sell_id,warehouse_id,partition_id')->where("id", "in", $ids)->where('firmid', $this->auth->firmid)->select();
            // 处理结果为列表
            for ($i = 0; $i < count($sell_id_arr); $i++) {
                if ($i == 0) {
                    $sell_id_list = $sell_id_arr[$i]['sell_id'];
                } else {
                    $sell_id_list .= ',';
                    $sell_id_list .= $sell_id_arr[$i]['sell_id'];
                }
            }


            //获取销售退货副表的参数
            $wp_arr = Db::name('ykjp_sell_return_p')
                    ->alias('p')
                    ->join('ykjp_sell_return r', 'p.sell_return_id = r.id')
                    ->field('p.nums,p.product_id,r.warehouse_id,r.partition_id')
                    ->where("p.sell_return_id", "in", $ids)
                    ->where('p.firmid', $this->auth->firmid)
                    ->where('r.firmid', $this->auth->firmid)
                    ->select();

            // 获取副表的wp_id
            for ($i = 0; $i < count($wp_arr); $i++) {
                $wp_id = Db::name('ykjp_wp_relationship')
                        ->field('id')
                        ->where('warehouse_id', $wp_arr[$i]['warehouse_id'])
                        ->where('partition_id', $wp_arr[$i]['partition_id'])
                        ->where('product_id', $wp_arr[$i]['product_id'])
                        ->where('firmid', $this->auth->firmid)
                        ->find();
                //判断是否存在相应的wp数据
                if ($wp_id == null) {
                    //插入相应的wp数据并赋值wp_id
                    Db::name('ykjp_wp_relationship')->insert([
                        'firmid' => $this->auth->firmid,
                        'product_id' => $wp_arr[$i]['product_id'],
                        'warehouse_id' => $wp_arr[$i]['warehouse_id'],
                        'partition_id' => $wp_arr[$i]['partition_id'],
                        'inventory' => 0,
                        'freeze' => 0,
                        'updatetime' => $time,
                    ]);
                    $wp_id = Db::name('ykjp_wp_relationship')->getLastInsID();
                    $wp_arr[$i]['wp_id'] = $wp_id;
                } else {
                    //赋值wp_id
                    $wp_arr[$i]['wp_id'] = $wp_id['id'];
                }
            }


            // 启动事务
            Db::startTrans();
            try {

                //一、更新销售退货单状态
                Db::name('ykjp_sell_return')->where("status_list", 3)->where('firmid', $this->auth->firmid)->where("id", "in", $ids)->update($data);

                //二、更新销售单状态
                Db::name('ykjp_sell')->where("status_list", 8)->where('firmid', $this->auth->firmid)->where("id", "in", $sell_id_list)->update(['status_list' => 9, 'updatetime' => $time]);

                //三、
                for ($i = 0; $i < count($wp_arr); $i++) {

                    //插入流水表
                    Db::name('ykjp_inventory_statement')->insert([
                        'firmid' => $this->auth->firmid,
                        'product_id' => $wp_arr[$i]['product_id'],
                        'warehouse_id' => $wp_arr[$i]['warehouse_id'],
                        'partition_id' => $wp_arr[$i]['partition_id'],
                        'number' => $wp_arr[$i]['nums'],
                        'type' => '销售退货',
                        'updatetime' => $time,
                    ]);

                    //更新关联表
                    Db::name('ykjp_wp_relationship')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['wp_id'])
                            ->update([
                                'inventory' => Db::raw('inventory+' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);

                    //更新商品表
                    Db::name('ykjp_product')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['product_id'])
                            ->update([
                                'inventory' => Db::raw('inventory+' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);

                    //更新仓库表
                    Db::name('ykjp_warehouse')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['warehouse_id'])
                            ->update([
                                'inventory' => Db::raw('inventory+' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);

                    // 更新库区表
                    Db::name('ykjp_partition')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['partition_id'])
                            ->update([
                                'inventory' => Db::raw('inventory+' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);
                }

                // 提交事务
                Db::commit();
                $this->success(null, null, array("result" => "success"));
            } catch (PDOException $e) {

                Db::rollback();
                $this->error('提交失败');
            } catch (Exception $e) {

                Db::rollback();
                $this->error('提交失败');
            }

            $this->error("提交失败");
        } elseif ($this->request->param("type") == "no") {  //驳回
            $cause = $this->request->param('cause');  //审核失败原因
            $data = array("status_list" => 4, "reviewer_id" => $this->auth->id, "updatetime" => time(), 'cause' => $cause);
            $update = $this->model
                    ->where("status_list", 3)
                    ->where('firmid', $this->auth->firmid)
                    ->where("id", "in", $ids)
                    ->update($data);

            if ($update) {
                $this->success(null, null, array("result" => "success"));
            }
            $this->error("operation fail");
        }

        $this->error("Illegal operation");
    }

}
